package bag;

import java.util.Arrays;

/**
 * Creared with IntelliJ IDEA.
 * Description:用顺序表实现栈 时间复杂度和空间复杂度都是O(1)
 * 同样用单链表也可以实现 但是  需要头插法  而且尾结点不好出去
 * 所以  应该 使用 双向链表 来实现  更加方便
 * User:yxd
 * Date:2022-01-15
 * Time:21:46
 */
public class MyStack {
    private int[] elem;
    private int usedSize;
    public MyStack(){
        this.elem = new int[5];
    }
    public void push(int val){
        if(isFull()){
            this.elem = Arrays.copyOf(elem,2 * elem.length);
        }
        this.elem[this.usedSize] = val;
        usedSize ++;
    }
    public boolean isFull(){
        if(this.usedSize == this.elem.length){
            return true;
        }
        return false;
    }
    public int pop(){
        if(isEmpty()){
            throw new RuntimeException("栈空了！");
        }
        int a = this.elem[usedSize - 1];
        this.usedSize--;
        return a;
    }
    public boolean isEmpty(){
        return this.usedSize == 0;
    }
    public int peek(){
        if(isEmpty()){
            throw new RuntimeException("栈空了！");
        }
        int a = this.elem[usedSize - 1];
        return a;
    }

    public static void main(String[] args) {
        MyStack stack = new MyStack();
        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.push(4);
        stack.push(5);//入栈
        System.out.println(stack.pop());//出栈
        System.out.println(stack.peek());//栈顶元素
        System.out.println(stack.isEmpty());//是否为空
    }
}
